package controllers

import (
	"io/ioutil"
	"time"

	"lsis/models"

	"github.com/astaxie/beego"
)

type ActiveController struct {
	BaseController
}

func (c *ActiveController) URLMapping() {
	c.Mapping("queryJoiners", c.QueryJoinCustormer)
	c.Mapping("query", c.Query)
	c.Mapping("create", c.Create)
	c.Mapping("del", c.Del)
	c.Mapping("join", c.Join)
	c.Mapping("mine", c.QueryMyActive)

}

type ActivesResp struct {
	TotalNum    int `json:"TotalNum"`
	CurrentPage int `json;"Page"`
	TotalPage   int `json:"TotalPage"`
}

// @Title 查询活动
// @Description 查询我参加的或者我创建的活动
// @Param   location   formData   string  true       "用户当前坐标,如:22.676114,113.9048777"
// @Param   session    formData   string  true       "session"
// @Param   create     formData   bool    false      "默认查询参加的活动"
// @Success 200 {object}  models.ActiveWithJoin true "用户信息数组 数组"
// @Failure 400
// @Failure 404
// @router /mine [post]
func (a *ActiveController) QueryMyActive() {

	location := a.GetString("location")
	creater, err := a.GetBool("create")
	if err != nil {
		beego.Error("get actives failed:", err)
		a.returnResult(errCodeGetActive, err.Error(), "")
	}

	var result []models.ActiveWithJoin

	if creater {
		result, err = models.QueryActivesWithCreate(a.user, location)
	} else {
		result, err = models.QueryActivesWithJoin(a.user, location)
	}

	if err != nil {
		beego.Error("get actives failed:", err)
		a.returnResult(errCodeGetActive, err.Error(), "")
	} else {
		a.returnResult(0, "success", result)
	}

}

// @Title 查询活动
// @Description 活动广场页面获取活动，如果传了activeId 则只返回一个活动详情
// @Param   location   formData   string  true       "用户当前坐标,如:22.676114,113.9048777"
// @Param   session    formData   string  true       "session"
// @Param   activeId   formData   int     false      "活动Id"
// @Success 200 {object}  models.ActiveWithJoin true "用户信息数组 数组"
// @Failure 400
// @Failure 404
// @router /query [post]
func (a *ActiveController) Query() {

	location := a.GetString("location")

	activeId, err := a.GetInt("activeId")
	if err != nil {
		activeId = 0
	}

	if activeId > 0 {
		actives, err := models.QueryActivesDetail(a.user, location, activeId)
		if err != nil {
			beego.Error("get actives failed:", err)
			a.returnResult(errCodeGetActive, err.Error(), "")
		} else {
			a.returnResult(0, "success", actives)
		}
	} else {

		actives, err := models.QueryActives(a.user, location)
		if err != nil {
			beego.Error("get actives failed:", err)
			a.returnResult(errCodeGetActive, err.Error(), "")
		} else {
			a.returnResult(0, "success", actives)
		}
	}
}

type active struct {
	Title       string `form:"Title"`
	StartTime   string `form:"StartTime"`
	EndTime     string `form:"EndTime"`
	Describtion string `form:"Describtion"`
	Address     string `form:"Addr"`
	Content     string `form:"Content"`
	ActiveImg   string `form:"ActiveImg"`
	Location    string `form:"Location"`
	NickName    string `form:"NickName"`
	WeChatId    string `form:"WeChatId"`
}

// @Title 创建活动
// @Description 创建一个活动
// @Param   location   formData   string  true       "用户当前坐标,如:22.676114,113.904877"
// @Param   session    formData   string  true       "session"
// @Param   Title      formData   string  true       "标题"
// @Param   StartTime formData   string  true        "开始时间: 2018-06-18 09:30"
// @Param   EndTime    formData   string  true       "结束时间: 2018-06-18 18:30"
// @Param   Describtion  formData   string  false    "描述"
// @Param   Addr       formData   string  true       "地址"
// @Param   Content    formData   string  false      "活动内容:1:美甲；2:美睫；3:护肤；4:纹眉；5:小姐姐美容；多项以英文逗号,隔开"
// @Param   ActiveImg  formData   string  false      "图片URL"
// @Param   NickName  formData   string  false       "NickName"
// @Param   WechatId  formData   string  false       "WeChatId"
// @Success 200 {object} controllers.result
// @Failure 400
// @Failure 404
// @router /create [post]
func (a *ActiveController) Create() {

	timeLayout := "2006-01-02 15:04"
	loc, _ := time.LoadLocation("Local") //重要：获取时区

	ob := active{}
	//json.Unmarshal(a.Ctx.Input.RequestBody, &ob)
	if err := a.ParseForm(&ob); err != nil {
		beego.Error("parse form failed", err)
		a.returnResult(errCodeActive, err.Error(), "")
		return
	}

	beego.Debug("recv:", string(a.Ctx.Input.RequestBody), ob)

	start, err := time.ParseInLocation(timeLayout, ob.StartTime, loc)
	if err != nil {
		beego.Error("time format wrong:", err, ob.StartTime)
		a.returnResult(errCodeActive, err.Error(), "")
		return
	}
	end, err := time.ParseInLocation(timeLayout, ob.EndTime, loc)
	if err != nil {
		beego.Error("time format wrong:", err)
		a.returnResult(errCodeActive, err.Error(), "")
		return
	}

	ac := models.Active{
		ActiveImg:   ob.ActiveImg,
		Title:       ob.Title,
		CreateTime:  time.Now(),
		StartTime:   start,
		EndTime:     end,
		Describtion: ob.Describtion,
		Address:     ob.Address,
		Status:      0,
		Content:     ob.Content,
		Location:    ob.Location,
		NickName:    ob.NickName,
		WeChatId:    ob.WeChatId,
	}

	Id, err := models.InsertActive(a.user, &ac)
	if err != nil {
		beego.Error("create active failed:", err)
		a.returnResult(errCodeActive, err.Error(), "")
	} else {
		a.returnResult(0, "success", Id)
	}
}

// @Title 删除活动
// @Description 删除一个活动
// @Param   location   formData   string  false      "用户当前坐标,如:22.676114,113.904877"
// @Param   session    formData   string  true       "session"
// @Param   activeId    formData   int    true       "activeId"
// @Success 200 {object} controllers.result
// @Failure 400
// @Failure 404
// @router /del [post]
func (a *ActiveController) Del() {

	id, err := a.GetInt("activeId")
	if err != nil {
		beego.Error("delete active failed ", err)
		a.returnResult(errCodeActive, err.Error(), "")
		return
	}

	err = models.DeleteActive(id, a.user)
	if err != nil {
		beego.Error("delete active failed ", err)
		a.returnResult(errCodeActive, err.Error(), "")
	} else {
		a.returnResult(0, "success", "")
	}
}

// @Title 参加活动
// @Description 用户报名参加一个活动
// @Param   location   formData   string  false      "用户当前坐标,如:22.676114,113.904877"
// @Param   session    formData   string  true       "session"
// @Param   activeId   formData   int     true       "activeId"
// @Param   name       formData   string  false       "姓名"
// @Param   tel        formData   string  false       "联系方式"
// @Param   department formData   string  false       "部门"
// @Success 200  {object} controllers.result
// @Failure 400
// @Failure 404
// @router /join [post]
func (this *ActiveController) Join() {

	activeId, err := this.GetInt("activeId")
	if err != nil {
		beego.Error("get active Id failed ", err)
		this.returnResult(errCodeActive, err.Error(), "")
		return
	}

	name := this.GetString("name")
	tel := this.GetString("tel")
	department := this.GetString("department")

	err = models.AddUserToActive(this.user, name, tel, department, activeId)
	if nil != err {
		beego.Error("join the active  failed ", err)
		this.returnResult(errCodeActive, err.Error(), "")
	} else {
		models.AddNewOrderByActive(this.user.Id, activeId, "")
		this.returnResult(0, "success", "")
	}
}

type custormer struct {
	Realname   string `json:"RealName"`
	Tel        string `json:"Telephone"`
	Department string `json:"DepartMent"`
	NickName   string `json:"nickName"`
	HeadImg    string `json:"icon"`
}

type joinUser struct {
	Total     int64       `json:"total"`
	Custormer []custormer `json:"custormer"`
}

// @Title 查询活动参与者
// @Description 查询活动参与人数
// @Param   location   formData   string  false       "用户当前坐标,如:22.676114,113.904877"
// @Param   session    formData   string  true       "session"
// @Param   activeId   formData   int     true       "activeId"
// @Success 200  {object} controllers.joinUser
// @Failure 400
// @Failure 404
// @router /queryJoiners [post]
func (this *ActiveController) QueryJoinCustormer() {

	var res joinUser

	activeId := this.GetString("activeId")
	num, result, err := models.QueryCustormerByActive(activeId)
	if nil != err {
		this.returnResult(errCodeGetActive, err.Error(), "")
		return
	}

	res.Total = num

	for _, row := range result {
		newCustormer := custormer{
			Realname:   row["RealName"].(string),
			Tel:        row["Telephone"].(string),
			Department: row["DepartMent"].(string),
			NickName:   row["NickName"].(string),
			HeadImg:    row["HeadImg"].(string),
		}

		res.Custormer = append(res.Custormer, newCustormer)
	}

	this.returnResult(0, "success", res)
}

/*
<form enctype="multipart/form-data" method="post">
    <input type="file" name="activeImg" />
    <input type="submit">
</form>
*/

type FormController struct {
	BaseController
}

// @Title 上传图片
// @Description 上传一张图片
// @Param   location   formData   string  true       "用户当前坐标,如:22.676114,113.904877"
// @Param   session    formData   string  true       "session"
// @Param   activeImg  formData   string  true    "图片内容"
// @Success 200  {object} controllers.result
// @Failure 400
// @Failure 404
// @router /upload [post]
func (c *FormController) Upload() {

	f, h, err := c.GetFile("activeImg")
	if err != nil {
		beego.Error("getfile err ", err)
		c.returnResult(2, err.Error(), "")
		return
	}

	defer f.Close()

	//filePath := "/tmp/upload/" + h.Filename
	//c.SaveToFile("activeImg", filePath)

	fileBuf, err := ioutil.ReadAll(f)
	if err != nil {
		beego.Error("read upload file failed,", err)
		c.returnResult(errCodeFileUp, "upload failed", "")
		return
	}

	filePath := c.session.Session + c.user.OpenId + h.Filename
	addToUploadTask(filePath, fileBuf)

	c.returnResult(0, "http://"+host+filePath, "")
}
